import requests
from lxml import etree
import parsel
import os

head = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
}
url1 = 'https://www.hexuexiao.cn/meinv/qingchunmeinv/'
list_html = requests.get(url1).text

list_slenctor = parsel.Selector(list_html)
url_list = list_slenctor.css('.waterfall_1box dt a::attr(href)').getall()
title_list = list_slenctor.css('.waterfall_1box dt a::text').getall()
for link, title in zip(url_list, title_list):

    print(f"正在爬取{title}")

    if not os.path.exists('img/'+title):
        os.mkdir('img/'+title)

    # link = 'https://www.hexuexiao.cn/a/129286-0.html'
    resp = requests.get(link, headers=head)
    resp.encoding = 'utf-8'
    # 获取数据
    html_data = resp.text


    # 解析数据
    selector = parsel.Selector(html_data)
    img_list = selector.css('.swiper-slide a img::attr(src)').getall()
    img_list = img_list[1:-1]
    for img_url in img_list:
        bin_img = img_url.replace('.300.jpg','')   # replace 替换
        img_data = requests.get(bin_img).content
        ing_name = bin_img.split('/')[-1]

        print(ing_name)

        with open(f'img/{title}/{ing_name}', mode='wb') as f:
            f.write(img_data)
